#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define UAL_TOP_DIR "/ual"
#define DO_NAME_HD    "do"
#define DO_ON_VALSTR  "0"
#define DO_OFF_VALSTR "1"

void show_help(void)
{
    printf ("使用说明: \n");
	printf ("[端口序号] [开关选择]\n");
	printf (" 参数说明:\n");
	printf ("          端口序号: 1~999\n");
	printf ("          开关选择: 0表示关闭, 1表示打开\n");
}

int ctrl_do(int doidx, int onoff)
{
	char  do_value_fpath[64];
	FILE *do_value_fphdl;

	memset(do_value_fpath,0,64);
#if 0
	system("echo 0 > /ual/do_on/value");
#endif

	sprintf(do_value_fpath,"/%s/%s%d/value", UAL_TOP_DIR, DO_NAME_HD, doidx);

	if ((do_value_fphdl = fopen(do_value_fpath, "rb+")) == NULL)
	{
		printf("无法打开文件: %s\n",do_value_fpath);
		exit(1);
	}

	if(onoff == atoi(DO_ON_VALSTR))
	{
		fprintf(do_value_fphdl, DO_ON_VALSTR);
	}else
	{
		fprintf(do_value_fphdl, DO_OFF_VALSTR);
	}
	fclose(do_value_fphdl);
#if 0
	system("echo 1 > /ual/do_on/value");
#endif
	return 0;
}


int main(int argc, char **argv)
{
	int doidx = -1;
	int onoff = -1;

	if(argc != 3)
	{
    	printf ("程序参数错误! \n");
		show_help();
		return -1;
	}
	doidx = atoi(argv[1]);
	if (0 == doidx)
	{
    	printf ("端口序号错误! \n");
		show_help();
		return -1;
	}

	onoff = atoi(argv[2]);
	if (0 != onoff && 1 != onoff)
	{
    	printf ("开关选择错误! \n");
		show_help();
		return -1;
	}

	if(1 == onoff)
	{
    	printf ("执行打开端口: %d\n", doidx);
		ctrl_do(doidx, atoi(DO_ON_VALSTR));
	}else
	{
    	printf ("执行关闭端口: %d\n", doidx);
		ctrl_do(doidx, atoi(DO_OFF_VALSTR));
	}
    printf ("OK\n");
	return 0;
}
